<?php

namespace App\Services;
use Intervention\Image\Facades\Image;

class ComposeImage
{
    protected $maps = [];

    public function generate($main_image,$save_path){
        // 加载主图像
        $image1 = Image::make($main_image);

        // 获取主图像宽度和高度
        $width = $image1->width();
        $height = $image1->height();

        // 创建一个新的图像
        $new_image = Image::canvas($width, $height);

        // 将主图像复制到新的图像中
        $new_image->insert($image1, 'top-left', 0, 0);

        $destroy = [];
        foreach ($this->maps as $item){
            $img = array_get($item,'img');
            $x = array_get($item,'x');
            $y = array_get($item,'y');
            $rotate = array_get($item,'rotate');

            // 加载贴图
            $map_image = Image::make($img);

            $map_width = $map_image->width();
            $map_height = $map_image->height();

            // 禁用锯齿
            //$map_image->blur(10);

            // 将贴图旋转20度
            $map_image->rotate($rotate);

            if($x == 'top-left'){

                $x = $width / 2 / 2 - $map_width/2;
                $y = $height / 8 - $map_height / 2;
            }elseif($x == 'top-right'){

                $x = $width - ($width / 2 / 2) - $map_width/2;
                $y = $height / 8 - $map_height / 2;

            }elseif($x == 'middle-left'){
                $x = $width / 2 / 2 - $map_width/2;
                $y = $height/2 - $map_height/2;

            }elseif ($x == 'middle-right'){
                $x = $width - ($width / 2 / 2) - $map_width/2;
                $y = $height/2 - $map_height/2;
            }elseif ($x == 'bottom-left'){
                $x = $width / 2 / 2 - $map_width/2;
                $y = $height-($height/3) + $map_height/2;

            }elseif ($x == 'bottom-right'){
                $x = $width - ($width / 2 / 2) - $map_width/2;
                $y = $height-($height/3) + $map_height/2;
            }
            $x = round($x);
            $y = round($y);


            // 将贴图复制到新图像中
            $new_image->insert($map_image,'top-left', $x, $y);

            $destroy[] = $map_image;
        }

        // 保存新图像
        //$new_image->save(public_path('new.jpg'));
        $new_image->save($save_path);

        // 释放内存
        $image1->destroy();
        $new_image->destroy();
        foreach ($destroy as $v){
            $v->destroy();
        }
        return $save_path;

    }

    public function addMaps($img,$rotate,$x,$y=null){
        $this->maps[] = [
            'img'=>$img,
            'x'=>$x,
            'y'=>$y,
            'rotate'=>$rotate
        ];
        return $this;
    }
}
